package com.spartez.farhorizons.client.map;

import com.gwtext.client.util.Format;
import com.gwtext.client.widgets.Panel;
import com.spartez.farhorizons.client.Calculator;
import com.spartez.farhorizons.client.FarHorizons;
import com.spartez.farhorizons.client.DataService.GravityTechLevelListener;
import com.spartez.farhorizons.client.DataService.SystemHoveredListener;
import com.spartez.farhorizons.client.data.ISystemDescr;

public class DistanceDisplayComponent extends Panel implements SystemHoveredListener, GravityTechLevelListener {
	public DistanceDisplayComponent() {
		FarHorizons.dataService.registerSystemHoveredListener(this);
		FarHorizons.dataService.registerGravityTechLevelListener(this);
		setBodyStyle("background-color:C3D9FF");
		setBorder(false);
	}

	public void systemHovered(ISystemDescr hoveredSystem) {
		refresh();
	}

	public void gravityTechLevel(int gravity) {
		refresh();
	}
	
	private void refresh() {
		final ISystemDescr selected = FarHorizons.dataService.getSelectedSystem();
		final ISystemDescr hoveredSystem = FarHorizons.dataService.getHoveredSystem();
		final int grav = FarHorizons.dataService.getCurrentGravity();
		
		if (selected != null && selected != hoveredSystem) {
			StringBuilder sb = new StringBuilder(Format.format("Distance from [{0} {1} {2}]", selected.getX(), selected.getY(), selected.getZ()));
			sb.append(Format.format(" to [{0} {1} {2}]", hoveredSystem.getX(), hoveredSystem.getY(), hoveredSystem.getZ()));
			sb.append(": ");
			final double range = Calculator.calcDistance(selected, hoveredSystem);
			sb.append(Math.ceil(range * 100d)/100d );
			if (grav > 0) {
				final double mishap = range * range / grav; 
				sb.append(Format.format(", Mishap {0}%", String.valueOf(Math.ceil(mishap * 100d)/100d)));
			}
			setHtml(sb.toString());
		}	
	}
}
